import {
  _decorator,
  Component,
  instantiate,
  Node,
  Prefab,
  UITransform,
} from 'cc';
import { DanmuChoicesItemController } from './DanmuChoicesItemController';
import { DataManager } from '../DataManager';
const { ccclass, property } = _decorator;

@ccclass('DanmuChoicesController')
export class DanmuChoicesController extends Component {
  @property(Prefab)
  danmuChoicesItemPrefab: Prefab | null = null;

  danmuChoicesItemCList: DanmuChoicesItemController[] = [];
  start() {}
  init() {
    this.node.children.forEach((child: Node) => {
      child.destroy();
    });
    this.danmuChoicesItemCList = [];
  }

  render(isEnemy: boolean) {
    const { gameData, role } = DataManager.instance;
    const cards = gameData.clients.find((client) => {
      if (!isEnemy) return client.role === role;
      else return client.role !== role;
    }).cards;
    // 初始化
    if (!this.danmuChoicesItemCList.length) {
      cards.forEach(() => {
        const danmuChoicesItem = instantiate(this.danmuChoicesItemPrefab);
        danmuChoicesItem.setParent(this.node);
        const danmuChoicesItemC = danmuChoicesItem.getComponent(
          DanmuChoicesItemController
        );
        this.danmuChoicesItemCList.push(danmuChoicesItemC);
      });
    }
    console.log('render danmu count ', cards, this.danmuChoicesItemCList);
    // 渲染
    const uiTrans = this.node.getComponent(UITransform);
    if (cards.every((card) => card.danmuCount === 0)) {
      const width = uiTrans.width / cards.length;
      this.danmuChoicesItemCList.forEach((danmuChoicesItemC, index) => {
        danmuChoicesItemC.render(
          cards[index].cardIndex,
          cards[index].danmuCount,
          width,
          cards[index].used
        );
      });
    } else {
      const totalCount = cards.reduce((total, card) => {
        return total + card.danmuCount;
      }, 0);
      this.danmuChoicesItemCList.forEach((danmuChoicesItemC, index) => {
        const baseWidth = 30; // 保底宽度
        const width =
          ((uiTrans.width - cards.length * baseWidth) / totalCount) *
            cards[index].danmuCount +
          baseWidth;
        danmuChoicesItemC.render(
          cards[index].cardIndex,
          cards[index].danmuCount,
          width,
          cards[index].used
        );
      });
    }
  }

  update(deltaTime: number) {}
}
